package com.wonderful.eyepetizer.data.di

import com.wonderful.eyepetizer.app.BASE_URL
import com.wonderful.eyepetizer.data.http.ApiService
import com.wonderful.eyepetizer.data.http.MyLoggingInterceptor
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

/**
 * Desc:
 * @Author: wonderful
 * @Time: 2024/2/20 10:48
 */
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {

    // 全局单例需要添加 @Singleton 注解
    @Singleton
    @Provides
    fun provideOKHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(MyLoggingInterceptor().apply {
                level = MyLoggingInterceptor.Level.BODY
            })
            .connectTimeout(20, TimeUnit.SECONDS)
            .build()
    }

    @Singleton
    @Provides
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder().baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()
    }

    @Singleton
    @Provides
    fun provideApiService(retrofit: Retrofit): ApiService {
        return create<ApiService>(retrofit)
    }

    private fun <T> create(retrofit: Retrofit, serviceClass: Class<T>): T =
        retrofit.create(serviceClass)

    private inline fun <reified T> create(retrofit: Retrofit): T = create(retrofit, T::class.java)
}